function varargout = p_pod(varargin)

% $Id: p_pod.m 327 2005-05-09 20:24:15Z odellj $
% P_POD Application M-file for p_pod.fig
%    FIG = P_POD launch p_pod GUI.
%    P_POD('callback_name', ...) invoke the named callback.
%
%   Main control panel for EROS analysis program suite
%   Reads default parameters from file "header.hdr" into structure "hdr." at
%   startup.
%
%   Ed Maclin - 3-12-03 et seq.
%   skips reading .elp & .mtg files if chan select not selected
%    if chan select OFF, must set hdr.mchans manually (via GUI?)
%
% Last Modified by GUIDE v2.5 18-May-2011 20:04:18

global hdr handles file_name home_path dist max_dist min_dist logid log_flg ...
        plot_e_pulse id_tags ch_sel_flg i_config ...
        evt_PathName avg_PathName

clc

if nargin == 0  % LAUNCH GUI

	fig = openfig(mfilename,'reuse');
    p_pod_id = '$Id: p_pod.m 327 2005-05-09 20:24:15Z odellj $';
    id_tags = cellstr(p_pod_id);
    
%     % force operator to select a header file
%     %
%     [fname,pname] = uigetfile('c:\data\*.hdr','Select the header file');
% 
% 	if fname ~= 0
% 		hdr.hdr_name = fname;
%         hdr.hdr_path = pname;
% 		load([pname fname],'-mat')
% 		sync_hdr
% 	end        

	% Generate a structure of handles to pass to callbacks, and store it. 
	handles = guihandles(fig);
        
    % changeIcon
    %
%     disp('Changing Icon')
%     jFrame=get(handles.figure1,'javaframe');
%     jIcon=javax.swing.ImageIcon('icon.gif');
%     jFrame.setFigureIcon(jIcon);
    
    handles.norm_flg=0;     % initialize action flags
    handles.pc_flg=0;
    handles.filt_flg=0;
    handles.avg_flg=0;
    handles.fft_flg=0;
    handles.corr_flg=0;  % Presumably to be removed.
    
    set(handles.Save_Norm,'Value',1);   % initialize save flags; 1 => save
    hdr.norm_save_flg=get(handles.Save_Norm,'Value');
    set(handles.Save_Pulse,'Value',1);
    hdr.pc_save_flg=get(handles.Save_Pulse,'Value');
    set(handles.Save_Filt,'Value',1);
    hdr.filt_save_flg=get(handles.Save_Filt,'Value');
    set(handles.Save_Avg,'Value',1);
    hdr.avg_save_flg=get(handles.Save_Avg,'Value');
    set(handles.Save_FFT,'Value',1);
    hdr.fft_save_flg=get(handles.Save_FFT,'Value');
    
    hdr.n_threshold=20;
    
    [logid, log_flg, plot_e_pulse_flg, ch_sel_flg] = initialize;
    [logid, log_file] = init_log;
    
    guidata(fig, handles);
    
	if nargout > 0
		varargout{1} = fig;
	end

elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK

	try
		if (nargout)
			[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
		else
			feval(varargin{:}); % FEVAL switchyard
		end
	catch
		disp(lasterr);
	end

end

% --------------------------------------------------------------------
function sync_hdr   % copy values from hdr.* to handles.* (e.g. update GUI)
                    % only need to update items in main window, popups update themselves
global hdr handles logid

fprintf('(debug) Syncing header...\n');
if logid ~= 1       % Print to the log file too.
    fprintf(logid,'(debug) Syncing header...\n');
end

set(handles.exp_name,'String',hdr.exp_name);
set(handles.data_path_str,'String',hdr.data_path);

% make sure n_digits (for zero padding) is set
%
if isfield(hdr,'n_digits')
    if hdr.n_digits==3
    set(handles.radiobutton27,'Value',1)
    elseif hdr.n_digits==4
        set(handles.radiobutton28,'Value',1)
    else
        disp('Setting file name to 4 digits!!!')
        set(handles.radiobutton28,'Value',1)
        hdr.n_digits=4
    end
else
    disp('hdr.n_digits doesn''t exist')
    disp('Setting file name to 4 digits!!!')
    set(handles.radiobutton28,'Value',1)
    hdr.n_digits=4
end


% --------------------------------------------------------------------
function varargout = do_Norm_Callback(h, eventdata, handles, varargin)

handles.norm_flg=get(h,'Value');
guidata(h,handles);

% --------------------------------------------------------------------
function varargout = do_Pulse_Callback(h, eventdata, handles, varargin)
global hdr

handles.pc_flg=get(h,'Value');
guidata(h,handles);

% --------------------------------------------------------------------
function varargout = do_Filt_Callback(h, eventdata, handles, varargin)
global hdr

handles.filt_flg=get(h,'Value');
guidata(h,handles);

% --------------------------------------------------------------------
function varargout = do_Avg_Callback(h, eventdata, handles, varargin)

handles.avg_flg=get(h,'Value');
guidata(h,handles);

% --------------------------------------------------------------------
function varargout = do_Corr_Callback(h, eventdata, handles, varargin)
global hdr

handles.corr_flg=get(h,'Value');
guidata(h,handles);

% --------------------------------------------------------------------
function varargout = Save_Norm_Callback(h, eventdata, handles, varargin)
global hdr

handles.Save_Norm_flg=get(h,'Value');
hdr.norm_save_flg=handles.Save_Norm_flg;
guidata(h,handles);

% --------------------------------------------------------------------
function varargout = Save_Pulse_Callback(h, eventdata, handles, varargin)
global hdr

handles.Save_Pulse_flg=get(h,'Value');
hdr.pc_save_flg=handles.Save_Pulse;
guidata(h,handles);

% --------------------------------------------------------------------
function varargout = Save_Filt_Callback(h, eventdata, handles, varargin)
global hdr

handles.Save_Filt_flg=get(h,'Value');
hdr.filt_save_flg=handles.Save_Filt_flg;
guidata(h,handles);

% --------------------------------------------------------------------
function varargout = Save_Avg_Callback(h, eventdata, handles, varargin)
global hdr

handles.Save_Avg_flg=get(h,'Value');
hdr.avg_save_flg=handles.Save_Avg_flg;
guidata(h,handles);

% --------------------------------------------------------------------
function varargout = zap_Norm_Callback(h, eventdata, handles, varargin)

% --------------------------------------------------------------------
function varargout = zap_Pulse_Callback(h, eventdata, handles, varargin)

% --------------------------------------------------------------------
function varargout = zap_Filt_Callback(h, eventdata, handles, varargin)

% --------------------------------------------------------------------
function varargout = zap_Avg_Callback(h, eventdata, handles, varargin)

% --------------------------------------------------------------------
function varargout = zap_corr_Callback(h, eventdata, handles, varargin)

% --------------------------------------------------------------------
function varargout = do_FFT_Callback(h, eventdata, handles, varargin)

handles.fft_flg=get(h,'Value');
guidata(h,handles);

% --------------------------------------------------------------------
function varargout = Save_FFT_Callback(h, eventdata, handles, varargin)
global hdr

handles.Save_Avg_flg=get(h,'Value');
hdr.avg_save_flg=handles.Save_Avg_flg;
guidata(h,handles);

% --------------------------------------------------------------------
function varargout = zap_FFT_Callback(h, eventdata, handles, varargin)

% --------------------------------------------------------------------
function varargout = pushbutton1_Callback(h, eventdata, handles, varargin)
global hdr file_name i_block dc ac ph adc aac aph n2 ssdc ssac ssph msg msgs...
    i_msg zap_flg mod_freq log_flg log_file plot_e_pulse_flg subj cf...
    ch_sel_flg n_good i_config evt_PathName avg_PathName

% Initialize the log.
%
[logid, log_file] = init_log;
logid=1;
%list=hdr.subj_list;
% list
msgs=cell(1);
msg='';
i_msg=1;

norm_path = '';
pc_path = '';
filt_path = '';

% if hdr.data_type(1:2) == 'no'
%     in_path=[hdr.data_path hdr.exp_name 'norm' hdr.data_type hdr.hi '-' hdr.lo '\'];

if handles.pc_flg    
%     in_path=[hdr.data_path 'pc' hdr.data_type hdr.hi '-' hdr.lo '\'];
    hdr.data_type = 'pc';
else if handles.norm_flg
        hdr.data_type = 'norm';
    else 
        message('Warning:  Neither pulse correction or normalization is selected.', handles);
        if log_flg, logid = fopen(log_file,'a'); end                        
        fprintf(logid,'Error:  Please select either pulse correction or normalization.\n');
        if log_flg, fclose(logid); end
        return;
    end
end

if handles.filt_flg
%     in_path=[hdr.data_path hdr.exp_name 'pc' hdr.hi '-' hdr.lo '\'];
%     filt_path = in_path;    
    out_path = [hdr.data_path hdr.exp_name 'filt' hdr.hi '-' hdr.lo '\'];
%     filt_out_path=in_path;
end

if handles.avg_flg
    evt_PathName = uigetdir([hdr.data_path hdr.exp_name 'evt'],'Select Event Folder')
    avg_PathName = uigetdir([hdr.data_path hdr.exp_name hdr.data_type hdr.hi '-' hdr.lo],'Select Avg Output Folder')
end

% expt = hdr.exp_name(1:end-1);

% This function will check p_pod variables and the existing files.
%ready_to_run;
% if ((hdr.low_pass==0) || (hdr.hi_pass==0)) && (handles.filt_flg == 1)
%     message('Warning:  Either Hi or Low pass is not set.', handles);
%     if log_flg, logid = fopen(log_file,'a'); end                        
%     fprintf(logid,'Error:  Either Hi or Low pass is not set.\r\n');
%     if log_flg, fclose(logid); end
%     return;
% end 

% fprintf(logid,'** GO function **\n');

for i_subj=1:max(size(hdr.subj_list))
    if hdr.n_digits==3
        subj=sprintf('%03.0f', hdr.subj_list(i_subj));
    elseif hdr.n_digits==4
        subj=sprintf('%04.0f', hdr.subj_list(i_subj));
    else
        disp('Need to set # of digits in file name (hdr.n_digits)')
        return
    end
    for i_SS=1:size(hdr.SS,1)
        ss1=deblank(hdr.SS(i_SS,:));
        
        fclose all; % allow file deletion below
        
        file_name=[hdr.data_path hdr.exp_name 'reg\' ss1 subj];
        
        % determine "good_dist_chs", if desired
        %
        if ch_sel_flg == 1
            
            % check for .elp and .mtg
            %
            fid_elp=fopen([file_name '.elp']);
            fid_mtg=fopen([file_name '.mtg']);
            if  fid_elp > 1   % does .elp exist?
                fclose(fid_elp);
            else
                error([file_name '.elp not available!']);
            end
            if  fid_mtg > 1   % does .mtg exist?
                fclose(fid_mtg);
            else
                error([file_name '.mtg file not available!']);
            end

            fid_dis=fopen([file_name cf '.dis']);

            if fid_dis > 1  % does distance (.dis) file exist?
                fclose(fid_dis);
            else
                mtg_dist(file_name,log_file)        % create .dis
            end

            % get # of chans for each montage (config) from .mtg file
            %
            disp(['Opening ' file_name '.mtg (p_pod line 321)']);
            montfid = fopen([file_name '.mtg']);
            fgetl(montfid);
            tline = fgetl(montfid); % get # of chs in each montage
            hdr.mchans=strread(tline,'%d');
            fclose(montfid);

            % attempt to load .gch info
            %
            hdr.gch_flg=ones(1,size(hdr.config,1));
            for i_config=1:size(hdr.config,1)
                cf=deblank(hdr.config(i_config,:));
                fid_gch=fopen([file_name cf '.gch']);
                if fid_gch <2   % does good channels (.gch) file exist?
                    disp([file_name cf '.gch does not exist'])
                    hdr.gch_flg(i_config)=0;    %no
                else
                    disp([file_name cf '.gch does exists'])
                    fclose(fid_gch);
                end
            end
            
            % if at least one .gch is missing, create missing files
            %
            if (sum(hdr.gch_flg) ~= size(hdr.config,1))
                disp(['creating (distance selected) ' file_name cf '.gch'])
                mtg_select(file_name,log_file)      % create .gch
            end

            fprintf('\n\nAttempting to delete %s\n',[file_name '_good.mtg']);
            cmd=sprintf('!del %s\n',[file_name '_good.mtg']);
            eval(cmd)

        else % if not selecting based on distance

%           get # of chans for each montage (config) from .mtg file
            %
            disp(['Opening ' file_name '.mtg']);
            montfid = fopen([file_name '.mtg']);
            fgetl(montfid);
            tline = fgetl(montfid); % get # of chs in each montage
            hdr.mchans=strread(tline,'%d');
            fclose(montfid);

            % save a 'dummy' (all chs) .gch file, for each config (mtg)
            %
            for i_config=1:length(hdr.config)
                cf=char(hdr.config(i_config));
                gch_file = [file_name cf '.gch'];
                fprintf(logid,'Saving (all) good channel file: %s\n',gch_file);
                fid=fopen(gch_file,'w');
                gchan=1:hdr.mchans(i_config);
                fprintf(fid,' %3.0d',gchan);
                fclose(fid);
            end

        end % ch_sel_flg

        % load modulation frequency file
        %
        if strcmp(hdr.exp_name(length(hdr.exp_name)),'\')
            expt=hdr.exp_name(1:end-1);
            mdf_file = [hdr.data_path hdr.exp_name 'opt\' expt '.mdf'];
        else
            expt=hdr.exp_name(1:end-1);
            mdf_file = [hdr.data_path hdr.exp_name 'opt\' expt '.mdf'];
        end

        if log_flg, logid = fopen(log_file,'a'); end
        if ~exist(mdf_file)
            msg = sprintf('MDF file %s does not exist\n',mdf_file);
%             disp(num2str(logid))
%             disp(msg)

            fprintf(logid,msg);
            message(msg, handles);
        else
            fprintf(logid,'(status)  Loading mdf file:  %s\n',mdf_file);
            mod_freqs=load(mdf_file,'-ASCII'); % mod freq file
        end
        if log_flg, fclose(logid); end
        
        for i_config=1:size(hdr.config,1)
            cf=deblank(hdr.config(i_config,:));
            
            hdr.n_chans=hdr.mchans(i_config);
            hdr.n_dets=hdr.n_chans/hdr.n_srcs;
            
            % define in & out paths
            %
            if handles.filt_flg 
                in_path = [hdr.data_path hdr.exp_name hdr.data_type hdr.hi '-' hdr.lo '\'];
            else
                in_path = [hdr.data_path hdr.exp_name hdr.data_type '00-00\'];
            end
            out_path = in_path;
            
            % redefine filename to strip .block number
            %
            file_name=[hdr.data_path hdr.exp_name 'reg\' ss1 subj];
            
            mod_freq=mod_freqs(i_config);   % modulation freq for this montage
            
            if log_flg, logid = fopen(log_file,'a'); end                        
            
            if ch_sel_flg == 0
                good_dist_chs=[1:hdr.n_chans];
            else
                % read "good channels" (.gch) file
                %
                fprintf(logid,'Loading gch file:  %s\n',[file_name cf '.gch']);
                good_dist_chs=load([file_name cf '.gch'],'-ASCII');
            end
			       
            skp_name=[hdr.data_path hdr.exp_name 'opt\' ss1 subj '.skp'];
            fprintf(logid,'(status)  Loading skip file:  %s\r\n',skp_name);
            
            if log_flg; fclose(logid); end

            if exist(skp_name)~=0
				skip=load(skp_name,'-ASCII');  % Open 'skip' file - missing/bad blocks == 0
                
                if handles.avg_flg==1   % zero accumulators and zap files prior to averaging                 

                    e_zero(log_file)
                    message(msg,handles)
                    zap_flg=get(handles.zap_Avg,'Value');
                    out_file=[avg_PathName '\' ss1 subj cf];
%                     disp(['file_name=' out_file])
%                     disp(['zap_flg=' num2str(zap_flg)])
                    if (zap_flg == 1)
                        disp(['Zapping ' out_file])
                        cmd=sprintf('!del %s\n',[out_file '.avg']);
                        disp(cmd)
                        eval(cmd) 
                        cmd=sprintf('!del %s\n',[out_file '.avm']);
                        disp(cmd)
                        eval(cmd) 
                        cmd=sprintf('!del %s\n',[out_file '.nir']);
                        disp(cmd)
                        eval(cmd)
%                         cmd=sprintf('!del %s\n',[out_file '.xls']);
%                         disp(cmd)
%                         eval(cmd)
                    end

                end % Avg initialization
                
				for i_block=1:hdr.n_blocks
                    
                    if skip(i_config,i_block)==1
                        block=sprintf('%03.0f', i_block);
                        file_name=[ss1 subj cf '.' block];
						
						if handles.norm_flg==1
                            zap_flg=get(handles.zap_Norm,'Value');
                            if zap_flg == 1
                                cmd=sprintf('!del %s\n',[hdr.data_path hdr.exp_name 'norm00-00\' file_name]);
                                eval(cmd)
                            end                            
                            b_norm(good_dist_chs,log_file);   %,'tall');
                            message(msg, handles)
                        end

                        if handles.pc_flg==1
                            zap_flg=get(handles.zap_Pulse,'Value');
                            if zap_flg == 1
                                cmd=sprintf('!del %s\n',[out_path file_name]);
                                eval(cmd)
                            end
                            e_pulse(good_dist_chs,log_file,plot_e_pulse_flg)
                            message(msg, handles)
						end
						
                        if handles.fft_flg==1
                            zap_flg=get(handles.zap_FFT,'Value');
                            if zap_flg == 1
                                k=findstr('.',file_name);
                                out_file_name=[file_name(1:k(1)) 'fft'];
                                cmd=sprintf('!del %s\n',[out_path out_file_name]);
                                eval(cmd)
                            end
                            e_fft(log_file)
                            message(msg, handles)
                        end
                        
						if handles.filt_flg==1
                            if (hdr.low_pass~=0) | (hdr.hi_pass~=0)
                                zap_flg=get(handles.zap_Filt,'Value');
                                if zap_flg == 1
                                    cmd=sprintf('!del %s\n',[out_path file_name]);
                                    eval(cmd)
                                end
                                e_filt(good_dist_chs,log_file)
                                message(msg, handles);
                            else
                                message('Neither Hi nor Low pass is set!', handles);
                            end
						end
						
						if handles.avg_flg==1
%                             fprintf('%s\n',out_path);
                            e_sum_qual(in_path,out_path,log_file)
                            message(msg, handles);
%                             disp('back from e_sum')
						end
                        
                    else
                        message(sprintf('Skipping block %2.0f\n',i_block), handles);
                    end % if skip(i_block)==1
                    
                    % Display the available HD Space.
                    %
%                     disp('checking HD space')
                    set(handles.hd_space,'String',check_hd);
	
				end % Block
                
                % Normalize sums (compute average)
                %
                if handles.avg_flg==1
	                e_avg(in_path,out_path,log_file)  % normalize and write out averaqes
%                     fprintf('e_avg exit into p_pod\n');
                    message(msg, handles)
                    e_o3d(in_path,out_path,log_file)
                    message(msg, handles)                    
                end
            else    % if .skp ~exists
                msg = sprintf('Warning:  %s missing\n',skp_name);
                message(msg,handles);
                if log_flg
                    logid = fopen(log_file,'a');
                    fprintf(logid,'Warning:  %s missing\r\n',skp_name);
                    fclose(logid);
                else
                    fprintf('Warning:  %s missing\r\n',skp_name);
                end                    
            end % if .skp
        end % config
        
        % if we're averaging write _good.mtg
        %
        if handles.avg_flg==1 
            file_name=[ss1 subj];
            mtg_good    % create *_good.mtg file
        end
             
	end % SS
end % Subj

msg=sprintf('Done.\n');
message(msg, handles);
% fprintf(logid,'** End of GO function **\n');
if log_flg
    logid = fopen(log_file,'a');
    fprintf(logid,'Done.\r\n');
    fclose(logid); 
end
fclose('all');

% --------------------------------------------------------------------
function varargout = File_menu_Callback(h, eventdata, handles, varargin)

% --------------------------------------------------------------------
function varargout = Open_file_Callback(h, eventdata, handles, varargin)
global hdr pname fname logid
pname='./'
[fname,pname,FilterIndex] = uigetfile([pname '*.hdr'],'Select the header file');

if fname ~= 0
	load([pname fname],'-mat');
    hdr.hdr_name = fname;
    hdr.hdr_path = pname;
    
    if isfield(hdr,'min_dist') ~= 1
        hdr.min_dist=1.5;
        hdr.max_dist=6.5;
        fprintf(logid,'No distance bounds in hdr; setting to default\n');
    end
    
    if isfield(hdr,'MinBeat') hdr = rmfield(hdr,'MinBeat'); end
    if isfield(hdr,'MaxBeat') hdr = rmfield(hdr,'MaxBeat'); end
    if isfield(hdr,'min_BPM') ~= 1
        hdr.min_BPM=45;
        hdr.max_BPM=105;
        fprintf(logid,'No BPM in hdr; setting to default\n');
    end

    fprintf('Opening file %s\n',[pname fname]);
    if logid ~= 1       % Print to the log file too.
        fprintf(logid,'Opening file %s\r\n',[pname fname]);
    end
	sync_hdr
end

% Display the available HD Space.  This accounts for switching headers that
% are based on different volumes.
%
% set(handles.hd_space,'String',check_hd);


% --------------------------------------------------------------------
function varargout = Save_file_Callback(h, eventdata, handles, varargin)
global hdr pname fname logid

fprintf(logid,'Saving %s\r\n',[pname fname]);

if fname ~= 0
	hdr.hdr_name = fname;
    hdr.hdr_path = pname;
	save([pname fname],'hdr','-mat');
    fprintf('Saving file %s\n',[pname fname]);
    if logid ~= 1       % Print to the log file too.
        fprintf(logid,'Saving file %s\r\n',[pname fname]);
    end
    sync_hdr
end

% --------------------------------------------------------------------
function varargout = Save_as_menu_Callback(h, eventdata, handles, varargin)
global hdr fname pname logid

% Save as is simplified to default to the current header location.
%
[fname,pname] = uiputfile([pname '*.hdr'],'Save Header File');

if fname ~= 0
    hdr.hdr_name = fname;
%     fname
    if isempty(findstr(fname,'.'))      % Add in the appropriate ext if needed.
        fname = [fname '.hdr'];
    end
    hdr.hdr_path = pname;
	save([pname fname],'hdr','-mat');
    fprintf(logid,'Saving file %s\n',[pname fname]);        
    if logid ~= 1       % Print to the log file too.
        fprintf(logid,'Saving file %s\r\n',[pname fname]);
    end
    sync_hdr
end

% --------------------------------------------------------------------
function varargout = Params_menu_Callback(h, eventdata, handles, varargin)

% --------------------------------------------------------------------
function varargout = PC_Params_Callback(h, eventdata, handles, varargin)

pc_params

% --------------------------------------------------------------------
function varargout = Filter_Params_Callback(h, eventdata, handles, varargin)

filter_params

% --------------------------------------------------------------------
function varargout = FFT_Params_Callback(h, eventdata, handles, varargin)

% --------------------------------------------------------------------
function varargout = Corr_Params_Callback(h, eventdata, handles, varargin)

 % Presumably, this will be removed.

% --------------------------------------------------------------------
function varargout = Avg_Params_Callback(h, eventdata, handles, varargin)
global hdr

avg_params

% --------------------------------------------------------------------
function varargout = Batch_menu_Callback(h, eventdata, handles, varargin)
global hdr

batch_params

% --------------------------------------------------------------------
function varargout = Anal_Params_Callback(h, eventdata, handles, varargin)

% --------------------------------------------------------------------
function varargout = Acq_Params_Callback(h, eventdata, handles, varargin)
global hdr
disp('p_pod 689; acq_params_callback')
Acq_params

% --------------------------------------------------------------------
function Quality_params_Callback(hObject, eventdata, handles)
% hObject    handle to Quality_params (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global hdr
disp('calling Quality_params.fig')
Quality_params

% --------------------------------------------------------------------
function avg_qual_params_Callback(hObject, eventdata, handles)
% hObject    handle to avg_qual_params (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global hdr
avg_qual_params

% --------------------------------------------------------------------
function dist_bounds_Callback(hObject, eventdata, handles)
global hdr

dist_params

% --------------------------------------------------------------------
function varargout = exp_name_Callback(h, eventdata, handles, varargin)
global hdr

Value=get(h,'String');

%  Check for trailing "\".
%
if Value(length(Value)) ~= '\'    
   Value = [Value '\'];
end        

set(handles.exp_name,'String',Value);
hdr.exp_name=Value;
guidata(h,handles);

% --------------------------------------------------------------------
function varargout = Make_skp_Callback(h, eventdata, handles, varargin)
global hdr log_file

[logid, log_file] = init_log;
make_skp(log_file)

% --------------------------------------------------------------------
function varargout = make_evt_Callback(h, eventdata, handles, varargin)
global hdr

make_evt_params

% --------------------------------------------------------------------
function varargout = data_path_str_Callback(h, eventdata, handles, varargin)
global hdr

Value = get(h,'String');

%  Check for trailing "\".
%
if Value(length(Value)) ~= '\'    
   Value = [Value '\'];
end        

set(handles.data_path_str,'String',Value);
hdr.data_path=Value;
guidata(h,handles);

% --------------------------------------------------------------------
function varargout = dir_tree_Callback(h, eventdata, handles, varargin)
global hdr

dos(['mkdir ' hdr.data_path hdr.exp_name]);
dos(['mkdir ' hdr.data_path hdr.exp_name 'opt']);
dos(['mkdir ' hdr.data_path hdr.exp_name 'beh']);
dos(['mkdir ' hdr.data_path hdr.exp_name 'evt']);
dos(['mkdir ' hdr.data_path hdr.exp_name 'o3d']);
dos(['mkdir ' hdr.data_path hdr.exp_name 'reg']);

% --------------------------------------------------------------------
function varargout = listbox1_Callback(h, eventdata, handles, varargin)

% --------------------------------------------------------------------
function message(msg, handles)
global msgs i_msg

msgs(i_msg)=cellstr(msg);
set(handles.listbox1,'String', msgs);

if i_msg > 3    % display last 3 line
    set(handles.listbox1,'ListboxTop',i_msg-3);
end

i_msg=i_msg+1;


% --------------------------------------------------------------------
function Exit_p_pod_Callback(hObject, eventdata, handles)
global logid

% Close the p_pod figure.
fprintf(logid,'Exiting p_pod at %s...\r\n',datestr(now,31));
fclose all;
close;

% --------------------------------------------------------------------
function [logid, log_file] = init_log
global hdr log_flg

% This function sets up the log generation and verbosity parameters.  If
% the log flag is unchecked ("Log to file" checkbox) this function just
% initializes the necessary variables to let other functions print to the
% screen.

logid = 1;          % Log ID of 1 prints to the screen.
log_file = '';      % Default to no log file.

if log_flg
    todayis = datestr(now,29);
    expt = hdr.exp_name;
    if expt(length(expt)) == '\'          % Strip the trailing '\' if it exists
        expt = expt(1:length(expt)-1);
    end        
    log_file = [hdr.hdr_path expt '-' todayis '.log'];
    logid = fopen(log_file,'a');
    fprintf(logid,'-----------------------------------------------------\r\n');
    fprintf(logid,'Log file for experiment %s at time: %s\r\n',expt,datestr(now,13));
    fprintf(logid,'-----------------------------------------------------\r\n\r\n');
    fclose(logid);
end

% --- Executes on button press in log_flag.
function log_flag_Callback(h, eventdata, handles)
global log_flg

log_flg = get(h,'Value');
guidata(h,handles);


% --- Executes on button press in plot_e_pulse.
function plot_e_pulse_Callback(h, eventdata, handles)
global plot_e_pulse_flg

% Hint: get(hObject,'Value') returns toggle state of plot_e_pulse
plot_e_pulse_flg = get(h,'Value');
guidata(h,handles);
fprintf('plot flag = %d\n',plot_e_pulse_flg);


% --- Initializes various values when p_pod first starts up.
function [logid, log_flg, plot_e_pulse_flg, ch_sel_flg] = initialize(h, eventdata, handles, varargin)
global hdr fname pname handles;

% Default the log to the screen until we get to the actual number crunching.    
%
logid = 1;
log_flg = 0;
plot_e_pulse_flg = 0;
ch_sel_flg = 0;

% This code defaults the header upon startup to whatever was the last
% header loaded (or rather, whatever is written in 'lasthdr.txt'
%
last_hdr_file = 'lasthdr.txt';
last_hdr_file_fid = fopen(last_hdr_file);

if last_hdr_file_fid > 0 % lasthdr.txt exists in current directory
    fprintf(logid,['Opening ' last_hdr_file '...\n']);
    last_hdr = fscanf(last_hdr_file_fid,'%s');
    last_hdr_fid = fopen(last_hdr);
    if last_hdr_fid > 0 && ~isempty(findstr(last_hdr,'.hdr'))
        load(last_hdr,'-mat');
    else
        fprintf('Error opening header.  Check %s.\n',last_hdr);
    end
else % if last header load fails, force operator to select a header file
    [fname,pname] = uigetfile('c:\data\*.hdr','Select the header file');

    if fname ~= 0
        hdr.hdr_name = fname;
        hdr.hdr_path = pname;
        load([pname fname],'-mat')
    end  
end

% however we got a .hdr, clean it up and sync it
%
if isfield(hdr,'min_dist') ~= 1
    hdr.min_dist=1.5;
    hdr.max_dist=6.5;
    fprintf(logid,'No dist bound in hdr; setting to default\n');
end
if isfield(hdr,'MinBeat') hdr=rmfield(hdr,'MinBeat'); end
if isfield(hdr,'MaxBeat') hdr=rmfield(hdr,'MaxBeat'); end
if isfield(hdr,'min_BPM') ~= 1
    hdr.min_BPM=45;
    hdr.max_BPM=105;
    fprintf(logid,'No BPM in hdr; setting to default\n');
end

sync_hdr

% Display the available HD Space.
%
% set(handles.hd_space,'String',check_hd);


% --- Executes on button press in ChanSelect.
% Hint: get(hObject,'Value') returns toggle state of ChanSelect
function ChanSelect_Callback(hObject, eventdata, handles)
global ch_sel_flg
ch_sel_flg=get(hObject,'Value');
guidata(hObject,handles);

% --------------------------------------------------------------------
function Help_menu_Callback(hObject, eventdata, handles)
% hObject    handle to Help_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --------------------------------------------------------------------
function About_menu_Callback(hObject, eventdata, handles)
% hObject    handle to About_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

about;

% --------------------------------------------------------------------
function capacity = check_hd
global hdr
% disp('Setting HD Capacity = 0')
capacity=0;
return

if isfield(hdr,'data_path')
    drive = hdr.data_path(1:2);
%     [s, w] = dos(['dir ' drive]);             % NOTE: Will not compile here.
else
%     [s, w] = dos('dir');
end

test = strfind(w,'Dir(s)');      % Find the known string.
test = test + 8;                 % Move ahead appropriately.
capacity = w(test:length(w));    % Snip.
separated = strread(capacity, '%s');
num = separated(1);
num = char(num);
% disp(['''num''=' num])
% Create an nx1 array of the digits, delimited by commas
num = strread(num,'%s','delimiter',',');
[count, blah] = size(num);

current = num(1);
for i = 2:count
    current = strcat(current,num(i));
end

% Convert to a number
current = char(current);
% disp(['''Current''=' current])
current = str2num(current);
% disp(['''Current''=' num2str(current)])

final = current / 1000000000;
if final >= 1
    capacity = sprintf('%.2f GiB free.\n',final);
else if (final * 1000) < 1
        final = final * 1000 * 1000;
        capacity = sprintf('%.2f KiB free.\n',final);
    else
        final = final * 1000;
        capacity = sprintf('%.2f MiB free.\n',final);
    end
end
% disp(['Capacity=' capacity]);

% --------------------------------------------------------------------
function ready_to_run

% Warning messages here?



% --------------------------------------------------------------------
% $Log: p_pod.m,v $
%
% 11/08 added 4 digit file names
%       and made 3 letter prefix does not have to match expt folder name
%
% Revision 1.63  2005/03/25 21:11:04  odellj
% Fixed and the default last header option that was resetting the bounds to 1.5, 6.  --Other changes as well, will be mentioned next checkin.
%
% Revision 1.62  2005/02/03 23:21:06  odellj
% logic to correct for hdr.exp_name having or not having a trailing '\\'.
%
% Revision 1.61  2005/02/03 22:31:24  odellj
% Cleaning up filt, save, and avg logic.
%
% Revision 1.60  2005/01/21 22:08:12  odellj
% Various small changes.
%
% Revision 1.59  2005/01/19 17:26:09  odellj
% Fixed the filter warning to come out only when filtering.
%
% Revision 1.58  2004/10/28 20:27:58  odellj
% Save As feature now adds '.hdr' automatically if no extension is applied to the entered savefile name.
%
% Revision 1.57  2004/10/20 21:51:02  odellj
% Removed verbose statement
%
% Revision 1.56  2004/10/19 19:52:07  odellj
% Adjustments from INM -> PSC
%
% Revision 1.55  2004/09/23 16:32:11  odellj
% Corrected 'check_hd' for switching headers that are on different drives.
%
% Revision 1.54  2004/09/21 19:14:36  odellj
% Rather, && for both low and hi pass filters not being set.
%
% Revision 1.53  2004/09/21 16:40:06  odellj
% fixed "filter not set" warning
%



% --------------------------------------------------------------------
function Initial_Quality_Params_Callback(hObject, eventdata, handles)
% hObject    handle to Initial_Quality_Params (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global hdr
Quality_params


% --------------------------------------------------------------------
function Avg_Quality_params_Callback(hObject, eventdata, handles)
% hObject    handle to Avg_Quality_params (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global hdr
avg_qual_params



% --- Executes during object creation, after setting all properties.
function radiobutton27_CreateFcn(hObject, eventdata, handles)
% if 
% disp('3 digits')
% hObject    handle to radiobutton27 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes during object creation, after setting all properties.
function radiobutton28_CreateFcn(hObject, eventdata, handles)
% disp('4 digits')
% hObject    handle to radiobutton28 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called


% --- Executes on button press in radiobutton27.
function radiobutton27_Callback(hObject, eventdata, handles)
global hdr
% disp('3 digits')
hdr.n_digits=3;
% hObject    handle to radiobutton27 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of radiobutton27


% --- Executes on button press in radiobutton28.
function radiobutton28_Callback(hObject, eventdata, handles)
global hdr
hdr.n_digits=4;
% disp('4 digits')
% hObject    handle to radiobutton28 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of radiobutton28


% --- Executes on key press with focus on Make_skp and none of its controls.
function Make_skp_KeyPressFcn(hObject, eventdata, handles)
global hdr
skip=ones(hdr.n_configs+1,hdr.n_blocks);
skip(hdr.n_configs+1,:)=[1:hdr.n_blocks];
disp(num2str(skip))
% hObject    handle to Make_skp (see GCBO)
% eventdata  structure with the following fields (see UICONTROL)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)


% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over Make_skp.
function Make_skp_ButtonDownFcn(hObject, eventdata, handles)
% hObject    handle to Make_skp (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function Documentation_Callback(hObject, eventdata, handles)
open('p_pod_manual.pdf')
% hObject    handle to Documentation (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
